import React, { memo, useEffect, useState, useRef } from "react";
import { useDispatch, useSelector, shallowEqual } from "react-redux";
import { UserPlayListStyle } from "./style";
import { NavLink } from "react-router-dom";
import { userPlaylistAction } from "../../../user/store/actionTypes";
import { getSizeImage } from "@/utils/format-utils";
import classnames from "classnames";

export default memo(function UserPlayList(props) {
  const dispatch = useDispatch();
  const userIID = JSON.parse(window.localStorage.getItem("userInfo")).data
    ? JSON.parse(window.localStorage.getItem("userInfo")).data.account.id
    : "";
  const [songId, setSongId] = useState(0);

  useEffect(() => {
    if (userIID) {
      dispatch(userPlaylistAction(userIID, 100));
    }
  }, [dispatch, userIID]);

  const state = useSelector(
    (state) => ({
      userPlayLists: state.getIn(["userInfo", "userPlaylistInfo"]),
    }),
    shallowEqual
  );

  return (
    <UserPlayListStyle>
      <ul>
        {state.userPlayLists.code === 200
          ? state.userPlayLists.playlist
              .slice(props.num[0], props.num[1])
              .map((item, index) => {
                const isCheck = item.id === songId;

                return (
                  <li
                    key={item.id}
                    className={classnames({ isCheck: isCheck })}
                    onClick={(e) => setSongId(item.id)}
                  >
                    <NavLink
                      to={{
                        pathname: "/mymusic/createSongList",
                        search: "?id=" + item.id,
                        state: { num: 1 },
                      }}
                    >
                      <img src={getSizeImage(item.coverImgUrl, 40)} alt="" />
                      <div className="playlist-text">
                        <p className="name">{item.name}</p>
                        <p className="trackCount">{item.trackCount}首</p>
                      </div>
                    </NavLink>
                  </li>
                );
              })
          : ""}
      </ul>
    </UserPlayListStyle>
  );
});
